package org.xhy.hrm.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import static org.xhy.hrm.constants.MQConstants.*;

@Configuration
public class MQConfig {

    //创建交换机
    @Bean
    public Exchange exchange(){
        return ExchangeBuilder.topicExchange(NAME_EXCHANGE_HRM_TOPIC).build();
    }

    //创建短信队列
    @Bean
    public Queue smsQueue(){
        return new Queue(NAME_QUEUE_HRM_SMS);
    }

    //创建邮箱队列
    @Bean
    public Queue emailQueue(){
        return new Queue(NAME_QUEUE_HRM_EMAIL);
    }

    //创建站内信队列
    @Bean
    public Queue stationQueue(){
        return new Queue(NAME_QUEUE_HRM_STATION);
    }

    //绑定短信队列               绑定的队列        到哪个交换机          routingKey     没有其他参数
    @Bean
    public Binding bindSmsQueue(){
        return BindingBuilder.bind(smsQueue()).to(exchange()).with("#.sms").noargs();
    }

    //绑定邮箱队列
    @Bean
    public Binding bindEmailQueue(){
        return BindingBuilder.bind(emailQueue()).to(exchange()).with("#.email").noargs();
    }

    //绑定站内信队列
    @Bean
    public Binding bindStationQueue(){
        return BindingBuilder.bind(stationQueue()).to(exchange()).with("#.station").noargs();
    }

    //自定义RabbitTemplate
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        //如果消息发送到MQ失败，把消息返回回来
        rabbitTemplate.setMandatory(true);
        return rabbitTemplate;
    }
}
